<template>
  <div class="page-container">
    <h2 class="page-title">门店管理</h2>

    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" class="search-form" label-width="90px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="门店名称">
              <el-input v-model="searchForm.storeName" placeholder="请输入门店名称" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="加盟商">
              <el-input v-model="searchForm.franchisee" placeholder="请输入加盟商姓名" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="联系电话">
              <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="省份">
              <el-select v-model="searchForm.province" placeholder="请选择省份" clearable style="width: 100%;">
                <el-option label="北京市" value="北京市" />
                <el-option label="天津市" value="天津市" />
                <el-option label="河北省" value="河北省" />
                <el-option label="山西省" value="山西省" />
                <el-option label="内蒙古自治区" value="内蒙古自治区" />
                <el-option label="辽宁省" value="辽宁省" />
                <el-option label="吉林省" value="吉林省" />
                <el-option label="黑龙江省" value="黑龙江省" />
                <el-option label="上海市" value="上海市" />
                <el-option label="江苏省" value="江苏省" />
                <el-option label="浙江省" value="浙江省" />
                <el-option label="安徽省" value="安徽省" />
                <el-option label="福建省" value="福建省" />
                <el-option label="江西省" value="江西省" />
                <el-option label="山东省" value="山东省" />
                <el-option label="河南省" value="河南省" />
                <el-option label="湖北省" value="湖北省" />
                <el-option label="湖南省" value="湖南省" />
                <el-option label="广东省" value="广东省" />
                <el-option label="广西壮族自治区" value="广西壮族自治区" />
                <el-option label="海南省" value="海南省" />
                <el-option label="重庆市" value="重庆市" />
                <el-option label="四川省" value="四川省" />
                <el-option label="贵州省" value="贵州省" />
                <el-option label="云南省" value="云南省" />
                <el-option label="西藏自治区" value="西藏自治区" />
                <el-option label="陕西省" value="陕西省" />
                <el-option label="甘肃省" value="甘肃省" />
                <el-option label="青海省" value="青海省" />
                <el-option label="宁夏回族自治区" value="宁夏回族自治区" />
                <el-option label="新疆维吾尔自治区" value="新疆维吾尔自治区" />
                <el-option label="台湾省" value="台湾省" />
                <el-option label="香港特别行政区" value="香港特别行政区" />
                <el-option label="澳门特别行政区" value="澳门特别行政区" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="地址">
              <el-input v-model="searchForm.address" placeholder="请输入地址关键词" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" class="search-btns-col">
            <el-form-item label-width="0">
              <div class="search-btns">
                <el-button type="primary" @click="onSearch" icon="el-icon-search">查询</el-button>
                <el-button @click="onReset" icon="el-icon-refresh">重置</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>门店列表</span>
          <el-button type="primary" @click="onAdd" icon="el-icon-plus">
            新增门店
          </el-button>
        </div>
      </template>
      <el-table :data="tableData" style="width: 100%" stripe v-loading="loading" element-loading-text="正在加载数据...">
        <el-table-column prop="storeName" label="门店名称" />
        <el-table-column prop="franchisee" label="加盟商" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="wechatGroup" label="微信群" />
        <el-table-column label="加盟日期">
          <template #default="scope">
            {{ scope.row.joinDate ? scope.row.joinDate.split('T')[0] : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="门店状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.closeStore === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.closeStore === 1 ? '营业中' : '已闭店' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <!-- 营业中的门店显示编辑和删除按钮 -->
              <template v-if="scope.row.closeStore === 1">
                <el-button
                  type="primary"
                  link
                  size="small"
                  icon="el-icon-edit"
                  @click="onEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  icon="el-icon-delete"
                  @click="onDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
              <!-- 已闭店的门店显示不可操作提示 -->
              <template v-else>
                <el-tag type="info" size="small" disabled>
                  闭店不可操作
                </el-tag>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model="pageNum"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next, jumper"
          class="custom-pagination"
        />
      </div>
    </el-card>

    <!-- 编辑门店弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑门店信息" width="600px" class="store-edit-dialog">
      <div v-if="editForm" class="store-edit-content">
        <el-form :model="editForm" label-width="120px" class="custom-edit-form">
          <el-form-item label="门店名称" prop="storeName">
            <el-input v-model="editForm.storeName" placeholder="请输入门店名称" />
          </el-form-item>
          <el-form-item label="加盟商" prop="franchisee">
            <el-input v-model="editForm.franchisee" placeholder="请输入加盟商姓名" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editForm.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="省份" prop="province">
            <el-input v-model="editForm.province" placeholder="请输入省份" />
          </el-form-item>
          <el-form-item label="微信群" prop="wechatGroup">
            <el-input v-model="editForm.wechatGroup" placeholder="请输入微信群名称" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="store-edit-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onEditSubmit" :loading="isSubmitting">
            {{ isSubmitting ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增门店弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增门店" width="600px" class="store-add-dialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px" class="custom-add-form">
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="addForm.storeName" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="加盟商" prop="franchisee">
          <el-input v-model="addForm.franchisee" placeholder="请输入加盟商姓名" />
        </el-form-item>
        <el-form-item label="开店省份" prop="province">
          <el-select v-model="addForm.province" placeholder="请选择省份" style="width: 100%;">
            <el-option label="北京市" value="北京市" />
            <el-option label="天津市" value="天津市" />
            <el-option label="河北省" value="河北省" />
            <el-option label="山西省" value="山西省" />
            <el-option label="内蒙古自治区" value="内蒙古自治区" />
            <el-option label="辽宁省" value="辽宁省" />
            <el-option label="吉林省" value="吉林省" />
            <el-option label="黑龙江省" value="黑龙江省" />
            <el-option label="上海市" value="上海市" />
            <el-option label="江苏省" value="江苏省" />
            <el-option label="浙江省" value="浙江省" />
            <el-option label="安徽省" value="安徽省" />
            <el-option label="福建省" value="福建省" />
            <el-option label="江西省" value="江西省" />
            <el-option label="山东省" value="山东省" />
            <el-option label="河南省" value="河南省" />
            <el-option label="湖北省" value="湖北省" />
            <el-option label="湖南省" value="湖南省" />
            <el-option label="广东省" value="广东省" />
            <el-option label="广西壮族自治区" value="广西壮族自治区" />
            <el-option label="海南省" value="海南省" />
            <el-option label="重庆市" value="重庆市" />
            <el-option label="四川省" value="四川省" />
            <el-option label="贵州省" value="贵州省" />
            <el-option label="云南省" value="云南省" />
            <el-option label="西藏自治区" value="西藏自治区" />
            <el-option label="陕西省" value="陕西省" />
            <el-option label="甘肃省" value="甘肃省" />
            <el-option label="青海省" value="青海省" />
            <el-option label="宁夏回族自治区" value="宁夏回族自治区" />
            <el-option label="新疆维吾尔自治区" value="新疆维吾尔自治区" />
            <el-option label="台湾省" value="台湾省" />
            <el-option label="香港特别行政区" value="香港特别行政区" />
            <el-option label="澳门特别行政区" value="澳门特别行政区" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="加盟日期" prop="joinDate">
          <el-date-picker
            v-model="addForm.joinDate"
            type="date"
            placeholder="请选择加盟日期"
            style="width: 100%;"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="微信群号" prop="wechatGroup">
          <el-input v-model="addForm.wechatGroup" placeholder="请输入微信群号（可选）" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="addForm.idNumber" placeholder="请输入身份证号（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="store-add-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddSubmit" :loading="isAdding">
            {{ isAdding ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();

const searchForm = ref({
  storeName: '',
  franchisee: '',
  phone: '',
  province: '',
  address: ''
});

const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(15);
const loading = ref(false);
const editDialogVisible = ref(false);
const editForm = ref(null);
const isSubmitting = ref(false);
const addDialogVisible = ref(false);
const addForm = ref({
  storeName: '',
  phone: '',
  franchisee: '',
  province: '',
  address: '',
  joinDate: null,
  wechatGroup: '',
  idNumber: ''
});
const addFormRules = {
  storeName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  franchisee: [{ required: true, message: '请输入加盟商姓名', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省份', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  joinDate: [{ required: true, message: '请选择加盟日期', trigger: 'change' }],
};
const addFormRef = ref(null);
const isAdding = ref(false);

// 获取门店列表
async function fetchTableData() {
  loading.value = true;
  try {
    let url = 'http://121.43.176.9:8090/api/store/by-user';
    
    // 根据员工类型决定是否传入userId
    if (Number(userStore.roleCode) !== 3) {
      // 非管理员（包括员工类型为-1），传入当前userId
      url += `?userId=${userStore.userId}`;
    }
    // 员工类型为3（管理员），不传入userId（获取所有门店）
    
    const response = await fetch(url);
    const res = await response.json();
    
    if (res.code === 200) {
      let stores = res.data || [];
      
      // 根据搜索条件过滤数据
      if (searchForm.value.storeName) {
        stores = stores.filter(store => 
          store.storeName && store.storeName.includes(searchForm.value.storeName)
        );
      }
      if (searchForm.value.franchisee) {
        stores = stores.filter(store => 
          store.franchisee && store.franchisee.includes(searchForm.value.franchisee)
        );
      }
      if (searchForm.value.phone) {
        stores = stores.filter(store => 
          store.phone && store.phone.includes(searchForm.value.phone)
        );
      }
      if (searchForm.value.province) {
        stores = stores.filter(store => 
          (store.province && store.province === searchForm.value.province) ||
          (store.address && store.address.includes(searchForm.value.province))
        );
      }
      if (searchForm.value.address) {
        stores = stores.filter(store => 
          store.address && store.address.toLowerCase().includes(searchForm.value.address.toLowerCase())
        );
      }
      
      // 按照加盟时间从近到远排序
      stores.sort((a, b) => {
        const dateA = a.joinDate ? new Date(a.joinDate) : new Date(0);
        const dateB = b.joinDate ? new Date(b.joinDate) : new Date(0);
        return dateB - dateA; // 降序排列，最新的在前
      });
      
      // 分页处理
      const startIndex = (pageNum.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      tableData.value = stores.slice(startIndex, endIndex);
      total.value = stores.length;
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error(res.msg || '获取门店列表失败');
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    ElMessage.error('获取门店列表失败');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 搜索
function onSearch() {
  pageNum.value = 1;
  fetchTableData();
}

// 重置
function onReset() {
  searchForm.value = {
    storeName: '',
    franchisee: '',
    phone: '',
    province: '',
    address: ''
  };
  pageNum.value = 1;
  fetchTableData();
}

// 分页
function handlePageChange(val) {
  pageNum.value = val;
  fetchTableData();
}

// 新增门店
function onAdd() {
  addForm.value = {
    storeName: '',
    phone: '',
    franchisee: '',
    province: '',
    address: '',
    joinDate: null,
    wechatGroup: '',
    idNumber: ''
  };
  addDialogVisible.value = true;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
}

// 提交新增
async function onAddSubmit() {
  if (!addFormRef.value) return;

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      isAdding.value = true;
      try {
                const requestBody = {
          storeName: addForm.value.storeName,
          phone: addForm.value.phone,
          franchisee: addForm.value.franchisee,
          province: addForm.value.province,
          address: addForm.value.address,
          joinDate: addForm.value.joinDate,
          employee0Id: userStore.userId, // 设置员工0ID为当前用户ID
          wechatGroup: addForm.value.wechatGroup,
          idNumber: addForm.value.idNumber
        };

        const response = await fetch('http://121.43.176.9:8090/api/store/join', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestBody)
        });

        const res = await response.json();

        if (res.code === 200) {
          ElMessage.success('门店添加成功');
          addDialogVisible.value = false;
          fetchTableData(); // 刷新列表
        } else {
          ElMessage.error(res.msg || '门店添加失败');
        }
      } catch (error) {
        console.error('添加门店失败:', error);
        ElMessage.error('门店添加失败');
      } finally {
        isAdding.value = false;
      }
    }
  });
}

// 编辑门店
function onEdit(row) {
  editForm.value = {
    storeId: row.storeId,
    storeName: row.storeName || '',
    franchisee: row.franchisee || '',
    phone: row.phone || '',
    address: row.address || '',
    province: row.province || '',
    wechatGroup: row.wechatGroup || ''
  };
  editDialogVisible.value = true;
}

// 提交编辑
async function onEditSubmit() {
  if (!editForm.value) return;
  
  isSubmitting.value = true;
  try {
    const requestBody = {
      storeId: editForm.value.storeId,
      storeName: editForm.value.storeName,
      franchisee: editForm.value.franchisee,
      phone: editForm.value.phone,
      address: editForm.value.address,
      province: editForm.value.province,
      wechatGroup: editForm.value.wechatGroup
    };
    
    // 当员工类型为非管理员时，在请求体中添加userId
    if (Number(userStore.roleCode) !== 3) {
      requestBody.userId = userStore.userId;
    }
    
    const response = await fetch('http://121.43.176.9:8090/api/store/update-store-and-oldstore', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    });
    
    const res = await response.json();
    
    if (res.code === 200) {
      ElMessage.success('门店信息更新成功');
      editDialogVisible.value = false;
      fetchTableData(); // 刷新列表
    } else {
      ElMessage.error(res.msg || '门店信息更新失败');
    }
  } catch (error) {
    console.error('更新门店信息失败:', error);
    ElMessage.error('门店信息更新失败');
  } finally {
    isSubmitting.value = false;
  }
}

// 删除门店
async function onDelete(row) {
  try {
    await ElMessageBox.confirm(
      `确定要删除门店"${row.storeName}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    );
    
    // 调用删除接口 - 根据门店ID删除单个门店
    const response = await fetch(`http://121.43.176.9:8090/api/store/delete/${row.storeId}`, {
      method: 'DELETE'
    });
    
    const res = await response.json();
    
    if (res.code === 200) {
      ElMessage.success(res.data || '门店删除成功');
      fetchTableData(); // 刷新列表
    } else {
      ElMessage.error(res.msg || '门店删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除门店失败:', error);
      ElMessage.error('删除门店失败');
    }
  }
}

onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.page-container {
  padding: 24px;
  background-color: #f5f7fa;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}



.search-card, .table-card {
  border-radius: 8px;
  margin-bottom: 24px;
  background-color: #fff;
}

.search-btns-col {
  display: flex;
  justify-content: flex-end;
}

.search-btns {
  display: flex;
  gap: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 17px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.action-buttons .el-button.is-link {
  font-size: 14px;
}

.store-edit-dialog .el-dialog__body {
  padding: 24px 32px 12px 32px;
  background: #f8fafd;
}

.store-edit-content {
  margin-bottom: 8px;
}

.store-edit-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.custom-edit-form {
  padding: 10px 0 0 0;
}

.custom-edit-form .el-form-item {
  margin-bottom: 18px;
}

.custom-edit-form .el-input {
  width: 100%;
}

.store-add-dialog .el-dialog__body {
  padding: 24px 32px 12px 32px;
  background: #f8fafd;
}

.custom-add-form {
  padding: 10px 0 0 0;
}

.custom-add-form .el-form-item {
  margin-bottom: 18px;
}

.custom-add-form .el-input {
  width: 100%;
}

.store-add-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
